package com.le.tester.imooc.oldfairy.test;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * createTime：2023/6/12 16:02
 * description：schedule
 */
public class Scheduler {
    //没有缓冲区的Queue,因此数据一来，立即处理和阻塞的两个极端
    //SynchronousQueue<Runnable> tasks = new SynchronousQueue<>(false);
    LinkedTransferQueue<Runnable> tasks = new LinkedTransferQueue<>();

    static AtomicInteger idCount = new AtomicInteger(0);

    public Scheduler(int workers) {
        //开启worker线程创建worker任务
        for (int i = 0; i < workers; i++) {
            new Thread(new Worker()).start();
        }
    }

    class Worker implements Runnable {
        int id;

        public Worker() {
            this.id = idCount.getAndIncrement();
        }

        @Override
        public void run() {
            while (true) {
                Runnable runnable = null;
                try {
                    runnable = tasks.take();
                    runnable.run();
                    System.out.format("work done by id=%d\n", id);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void submit(Runnable r) throws InterruptedException {
//        if (!tasks.offer(r)) {
//
//            //放进synchronizedQueue fail-->sleep
//            Thread.sleep(1);
        //创建了新的线程
//            new Thread(new Worker()).start();
//
//        }
        //限定了初始化的worker,
        //tasks.offer(r);

        if (!tasks.tryTransfer(r)) {
            Thread.sleep(1);
            new Thread(new Worker()).start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Scheduler scheduler = new Scheduler(5);
        for (int i = 0; i < 1000; i++) {
            int localI = i;
            Thread.sleep(1);
            scheduler.submit(() -> {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }


}
